const fs = require("fs")
const path = require("path")
const crypto = require("crypto")

// 生成RSA密钥对
function generateRSAKeyPair() {
  console.log("正在生成RSA密钥对...")
  const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
    modulusLength: 2048,
    publicKeyEncoding: {
      type: "spki",
      format: "pem"
    },
    privateKeyEncoding: {
      type: "pkcs8",
      format: "pem"
    }
  })

  const keyDir = path.join(__dirname, "../keys")
  if (!fs.existsSync(keyDir)) {
    fs.mkdirSync(keyDir, { recursive: true })
  }

  fs.writeFileSync(path.join(keyDir, "rsa_public.pem"), publicKey)
  fs.writeFileSync(path.join(keyDir, "rsa_private.pem"), privateKey)

  console.log("RSA密钥对已生成")
  return { publicKey, privateKey }
}

// 使用RSA公钥加密AES密钥
function encryptAESKey(aesKey, publicKey) {
  const encryptedKey = crypto.publicEncrypt(
    {
      key: publicKey,
      padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
    },
    aesKey
  )
  return encryptedKey
}

// 使用RSA私钥解密AES密钥
function decryptAESKey(encryptedAESKey, privateKey) {
  const decryptedKey = crypto.privateDecrypt(
    {
      key: privateKey,
      padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
    },
    encryptedAESKey
  )
  return decryptedKey
}

// 生成16字节的AES加密密钥
function generateAESKey() {
  return crypto.randomBytes(16)
}

// 创建密钥信息文件
function createKeyInfoFile(keyInfoPath, keyUri, keyPath, iv = null) {
  const ivString = iv ? iv.toString("hex") : ""
  const keyInfoContent = `${keyUri}\n${keyPath}\n${ivString}`
  fs.writeFileSync(keyInfoPath, keyInfoContent)
  return keyInfoPath
}

module.exports = {
  generateRSAKeyPair,
  encryptAESKey,
  decryptAESKey,
  generateAESKey,
  createKeyInfoFile
}
